const {app, Tray, BrowserWindow, Menu, shell} = require('electron')
const path = require("path")
const logger = require('electron-log')
const {screen} = require('electron');
const { nativeImage } = require('electron');

const iconNameWindows = "tray-windows.png";
const iconNameMac = "tray-mac.png";

const transparent = "transparent.ico";
const iconNameInfo = "tray-info.ico";

let iconPath;

if (process.env.NODE_ENV !== 'development') {
    iconPath = "icon";
} else {
    iconPath = "public";
}


let trayImage ;
let trayImageInfo;
let trayImageTransparent ;

function initIcon() {
    if (myWindows.systemType === "Windows") {
        trayImage =myWindows.appPath + iconPath +path.sep+ iconNameWindows;
    } else if (myWindows.systemType === "MacOS") {
        trayImage =myWindows.appPath + iconPath +path.sep+ iconNameMac;
    }else if(myWindows.systemType === "Linux"){
        trayImage =myWindows.appPath + iconPath +path.sep+ iconNameWindows;
    }

    trayImageInfo = myWindows.appPath+iconPath +path.sep+ iconNameInfo;
    trayImageTransparent = myWindows.appPath+iconPath +path.sep+ transparent;

}

//初始化托盘
exports.newTray = function () {
    initIcon();

    logger.info("trayImage:" + trayImage)
    const image = nativeImage.createFromPath(trayImage);
    image.setTemplateImage(true);
    myWindows.appTray = new Tray(image);
    myWindows.appTray.setToolTip("健身追踪");

    toggleWindow();
    createMenu();
}

//托盘点击事件处理
function trayClick() {

       myWindows.mainWindow.show();

}


let trayBounds, point, isLeave = true;

//点击托盘图标切换窗口显示隐藏
function toggleWindow() {
    myWindows.appTray.on("click", () => {
           myWindows.mainWindow.show();
        // trayClick();
    });
    // //监听鼠标双击
    // myWindows.appTray.on("double-click", () => {
    //     trayClick();
    // });

    //鼠标放上去显示
    myWindows.appTray.on("mouse-enter", () => {
        logger.info("mouse-enter");
    });
    myWindows.appTray.on("mouse-leave", () => {
        logger.info("mouse-leave");

    });
    myWindows.appTray.on("mouse-move", (event, bounds) => {
        if (isLeave) {
            //触发mouse-enter
            isLeave = false;
            checkTrayLeave();
            mouseEnter();
        }
    });


}

let timerOfCheckTrayLeave = null;


//检测鼠标是否在托盘图标上
function checkTrayLeave() {
    if(timerOfCheckTrayLeave){
        clearInterval(timerOfCheckTrayLeave);
    }
    timerOfCheckTrayLeave = setInterval(() => {
        //判断托盘是否被销毁
        if (!myWindows.appTray) {
            clearInterval(timerOfCheckTrayLeave);
            return;
        }

        trayBounds = myWindows.appTray.getBounds();
        point = screen.getCursorScreenPoint();
        if (!(trayBounds.x < point.x && trayBounds.y < point.y && point.x < (trayBounds.x + trayBounds.width) && point.y < (trayBounds.y + trayBounds.height))) {
            //触发mouse-leave
            clearInterval(timerOfCheckTrayLeave);
            isLeave = true;
            mouseLeave();
        }
    }, 100)
}

function mouseLeave() {

    if (isBlink) {

    }

}


function mouseEnter() {

    if (isBlink) {

    }
}

//右键菜单
function createMenu() {
    const contextMenuTemplate = [
        {
            label: "显示窗口",
            click: function () {
                myWindows.mainWindow.show();
            }
        }
    ];

    // 如果是mac系统，则不展现“查看日志”菜单项
    if (process.platform !== 'darwin') {
        contextMenuTemplate.push({
            label: "查看日志",
            click: function () {
                try {
                    logger.info("查看日志");
                    let logfile = path.dirname(app.getPath("exe")) + "\\resources\\server\\logs";
                    logger.info("logfile--->" + logfile);
                    shell.openPath(logfile);
                } catch (e) {
                    logger.info("error--->" + e);
                }
            }
        });
    }
    contextMenuTemplate.push(
        {
            label: "退出程序",
            click: () => {
                app.quit();
            },
        })

    const contextMenu = Menu.buildFromTemplate(contextMenuTemplate);
    myWindows.appTray.setContextMenu(contextMenu);
}


//托盘闪烁定时器
let timerForBlink = null;

let isBlink = false;

//实现托盘闪烁
function blinkTray() {
    isBlink = true;

    //windows系统托盘闪烁
    if (myWindows.systemType === "Windows") {
        if (myWindows.systemVersion === "Windows Server 2019") {
            //Windows Server 2019 不能默认不显示透明图片，所以托盘不闪烁只显示图标。其他版本根据情况适配
            myWindows.appTray.setImage(trayImageInfo);
        } else {
            let count = 0;
            if (timerForBlink) {
                clearInterval(timerForBlink);
            }
            timerForBlink = setInterval(() => {
                if (count % 2 == 0) {
                    myWindows.appTray.setImage(trayImage);
                } else {
                    myWindows.appTray.setImage(trayImageTransparent);
                }
                count++;
                if (count > 50) {
                    count = 0;
                }
            }, 500);
        }
    }
    else   if (myWindows.systemType === "MacOS") {
        // myWindows.appTray.setImage(trayImageInfo);
    }


}

function stopBlinkTray() {
    try{
        isBlink = false;
        myWindows.appTray.setImage(trayImage);
        if (timerForBlink) {
            clearInterval(timerForBlink);
        }
    }catch (e){
        logger.error("stopBlinkTray error:"+e)
    }

}


exports.blinkTray = blinkTray;
exports.blinkTrayStop = stopBlinkTray;


